package com.motu.monstercity.server.game.logichandler;

import com.motu.monstercity.module.common.network.RequestParam;
import com.motu.monstercity.module.common.utility.Constant;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.CsGameDating.*;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.maintask.TaskAchieve;
import com.motu.monstercity.server.game.commondata.system.SystemConstant;
import com.motu.monstercity.server.game.commondata.system.UserExp;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.model.EntityManager;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonArray;
import io.vertx.ext.auth.User;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import static com.motu.monstercity.server.game.logic.DatingManager.*;


public class DatingHandler {
    // CMD_GAME_DATING_INFO = 70901; //请求约会信息,更新约会精力
    public static Object CMD_GAME_DATING_INFO(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        CSGameDatingInfoResponse.Builder response = CSGameDatingInfoResponse.newBuilder();
        PBUserData.Builder pbUserData = response.getUserBuilder();
        UserDating userDating = DatingManager.getUserDating(userId);
        ProtoDataUtils.updatePBUserData(pbUserData, userDating, true);

        List<UserDatingSecretary> userDatingSecretaryList = getUserDatingSecretaryList(userId);
        for (UserDatingSecretary userDatingSecretary : userDatingSecretaryList) {
            ProtoDataUtils.updatePBUserData(pbUserData, userDatingSecretary, true);
        }
        return response;
    }

    //CMD_GAME_DATING_DATING = 70902; //请求约会
    public static Object CMD_GAME_DATING_DATING(RequestParam clientParam) throws Exception {
        CSGameDatingDatingRequest request = CSGameDatingDatingRequest.parseFrom(clientParam.getData());
        CSGameDatingDatingResponse.Builder response = CSGameDatingDatingResponse.newBuilder();

        PBUserData.Builder pbUserData = response.getUserBuilder();
        long userId = clientParam.getUserId();
        int type = request.getType();

        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserAffair userAffair = GameUser.getUserAffair(userId);
        UserStage userStage = FightManager.getUserStage(userId);
        boolean isOneKey = type == 1 ? true : false;// 是否一键约会
        if (isOneKey && !SystemManager.checkModuleOpen(userInfo, userAffair, userStage, SystemConstant.SYSTEM_MODULE_ID_DATING_ONEKEY))  {
            return ErrorWord.WRONG_STATUS;// 未解锁一键约会的功能
        }
        UserExp userExp = GameDataManager.getUserExp(userInfo.getLevel());
        if (userExp == null) {
            return ErrorWord.NOT_DATA;
        }
        UserDating userDating = DatingManager.getUserDating(userId);
        if (userDating.getStrength() <= 0) {
            return ErrorWord.TIMES_LACK;// 体力不足
        }

        int datingNum = isOneKey ? userDating.getStrength() : 1;// 约会次数
        UserPower userPower = GameUser.getUserPower(userId);
        JsonArray partnerJsonArray = userPower.getPartnerIdArray();// 干员id列表,
        JsonArray secretaryJsonArray = EntityManager.getEntityKeyList(UserSecretary.class, userId);// 秘书id列表
        ConcurrentHashMap<Integer, UserPartner> userpartnerList = new ConcurrentHashMap<>();// 缓存下来，避免重复取值
        ConcurrentHashMap<Integer, UserSecretary> userSecretaryList = new ConcurrentHashMap<>();// 缓存下来，避免重复取值

        if (partnerJsonArray.size() == 0 || secretaryJsonArray.size() == 0) {
            return ErrorWord.NOT_DATA_1;// 未获得干员或是秘书
        }

        UserChildInfo userChildInfo = ChildManager.getUserChildInfo(userId);
        List<UserChildCls> userChildClsList = ChildManager.getUserChildClsList(userId);
        userChildClsList.sort(Comparator.comparingLong(UserChildCls::getClsId));// 按id 从小到大排序

        for (int i=0; i<datingNum; i++) {
            DatingManager.doDating(response, userInfo, userChildInfo, userDating, userChildClsList, partnerJsonArray, secretaryJsonArray, i, userpartnerList, userSecretaryList);
        }

        userDating.subStrength(userInfo, datingNum, LogType.DATING_DATING);
        userDating.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userDating);

        userChildInfo.update();

        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_3, datingNum);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_3, datingNum);
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_115, datingNum);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_115, datingNum);
        return response;
    }

    //CMD_GAME_DATING_SECRETARY_DATING = 70903; //请求密会
    public static Object CMD_GAME_DATING_SECRETARY_DATING(RequestParam clientParam) throws Exception {
        CSGameDatingSecretaryDatingRequest request = CSGameDatingSecretaryDatingRequest.parseFrom(clientParam.getData());
        CSGameDatingSecretaryDatingResponse.Builder response = CSGameDatingSecretaryDatingResponse.newBuilder();
        int result = 0;
        //1.获取协议数据并验证合法性
        long userId = clientParam.getUserId();
        int secretaryId = request.getSecretaryId();
        UserSecretary userSecretary = SecretaryManager.getUserSecretary(userId, secretaryId);
        if (null == userSecretary) {
            return ErrorWord.NOT_DATA;
        }
        int partnerId = request.getPartnerId();
        UserPartner userPartner = PartnerManager.getUserPartner(userId, partnerId);
        if (null == userPartner) {
            return ErrorWord.NOT_DATA;
        }
        //2.验证是否满足条件
        UserInfo userInfo = GameUser.getUserInfo(userId);
        int datingType = request.getDatingType();
        PBUserData.Builder pbUserData = response.getUserBuilder();
        //消耗道具
        List<RewardItem> needItem = new ArrayList<>();
        //奖励道具
        UserDatingSecretary userDatingSecretary = DatingManager.getUserDatingSecretary(userId, secretaryId);
        if (userDatingSecretary == null) {
            userDatingSecretary = new UserDatingSecretary(userId, secretaryId);
            userDatingSecretary.doCreate();
        }
        if (datingType == DATING_DATING_TYPE_OUT_DOOR) {
            DatingManager.takeNeedItemNum(userDatingSecretary, needItem);
        } else if (datingType == DATING_DATING_TYPE_DINNER) {
            DatingManager.takeNeedItemNum(needItem);
        } else {
            return ErrorWord.NOT_DATA;
        }
        if (!BagManager.checkNeedItemNum(userInfo, needItem)) {
            return ErrorWord.ITEM_LACK;
        }
        //3.执行消耗
        RewardManager.subReward(userInfo, needItem, pbUserData, LogType.DATING_SECRETARY_DATING);
        //4.执行产出
        RewardItem rewardItem = DatingManager.takeRewardItemNum(userId, userSecretary, datingType);// 获得的羁绊值
        RewardManager.addReward(userInfo, rewardItem, pbUserData, LogType.DATING_SECRETARY_DATING, userSecretary.getSecretaryId());
        //子嗣产生成功时候约会成功，否则失败
        List<UserChildCls> userChildClsList = ChildManager.getUserChildClsList(userId);
        userChildClsList.sort(Comparator.comparingLong(UserChildCls::getClsId));// 按id 从小到大排序
        for (UserChildCls userChildCls : userChildClsList) {
            if (userChildCls.getIsStudy() == 0) {
                // 添加子嗣
                boolean isTwins = Tool.checkRandom(AllParam.CHILD_IS_TWINS / Constant.HUNDRED);//随机子嗣是否双胞胎
                if (datingType == DATING_DATING_TYPE_DINNER){
                    isTwins = true;
                }
                ChildManager.createChild(pbUserData, userChildCls, userPartner, userSecretary, isTwins);
                userChildCls.update();
                ProtoDataUtils.updatePBUserData(pbUserData, userChildCls);
                result = 1;
                break;
            }
        }
        //5.记录数据
        if (datingType == DATING_DATING_TYPE_OUT_DOOR) {
            userDatingSecretary.addDatingCount(1);
            userDatingSecretary.putLastDatingTime(TimeUtils.getCurTime());
            userDatingSecretary.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userDatingSecretary);
        }
        if (datingType == DATING_DATING_TYPE_OUT_DOOR) {
            MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_195, 1);// 更新主线任务,成就,日常任务的进度
            RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_195, 1);
        } else if (datingType == DATING_DATING_TYPE_DINNER) {
            MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_196, 1);// 更新主线任务,成就,日常任务的进度
            RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_196, 1);
        }
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_197, 1);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_197, 1);
        //6.返回结果
        ProtoDataUtils.updatePBUserData(pbUserData, userSecretary);
        response.setResult(result);
        response.setSecretaryId(userSecretary.getSecretaryId());
        response.setPartnerId(userPartner.getPartnerId());

        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_3, 1);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_3, 1);
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_115, 1);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_115, 1);
        return response;
    }


}
